package org.tp.framework.filter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.tp.framework.adapt.RequestParamAdapt;
import org.tp.framework.annotation.ResponseBody;
import org.tp.framework.constant.Constant;
import org.tp.framework.container.MvcMappingContainer;
import org.tp.framework.mapping.Mapping;
import org.tp.framework.util.JsonUtils;
import org.tp.framework.util.StringUtils;

@SuppressWarnings("serial")
public class DispetchServlet extends HttpServlet {

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constant.UTF8);
		response.setCharacterEncoding(Constant.UTF8);
		String requestPath = request.getServletPath();
		if (!MvcMappingContainer.containUrl(requestPath)) {
			response.getWriter().println("page not fonund !!!!!!");
			response.setStatus(404);
			return;
		}
		Mapping mapping = MvcMappingContainer.getMapping(requestPath);
		String requestMethod = request.getMethod();
		if (!mapping.getRequestMethod().equals(requestMethod)) {
			System.out.println(request.getMethod());
			response.getWriter().println("request method error !!!!!!");
			response.setStatus(405);
			return;
		}

		Object[] params = RequestParamAdapt.getParam(mapping.getParamMap(), mapping.getMethod().getParameterTypes(),
				request, response, request.getSession());
		try {
			Object result = mapping.getMethod().invoke(mapping.getObject(), params);
			if (result == null) {
				return;
			}

			ResponseBody body = mapping.getMethod().getAnnotation(ResponseBody.class);
			if (body != null) {
				response.setContentType("application/json");
				response.getWriter().write(JsonUtils.objToStr(result));
				return;
			}

			String resultViewName = StringUtils.toString(result);
			String viewPath = getServletContext().getInitParameter("viewPath");
			String rspView = viewPath + "/" + resultViewName;
			request.getRequestDispatcher(rspView).forward(request, response);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

}
